package org.elsfs.cloud.module.ai.api.service;

import dev.langchain4j.data.segment.TextSegment;
import dev.langchain4j.store.embedding.EmbeddingStore;
import dev.langchain4j.store.embedding.pgvector.PgVectorEmbeddingStore;
import org.elsfs.cloud.module.ai.api.entity.AiEmbeddingStore;
import org.elsfs.cloud.module.ai.api.enums.StoreType;

import java.util.Objects;

public interface AiEmbeddingStoreService {

    /**
     * Retrieves an embedding store containing text segments for the specified store ID.
     *
     * @param storeId the unique identifier of the embedding store to retrieve
     * @return an instance of {@code EmbeddingStore<TextSegment>} associated with the given store ID
     */
    EmbeddingStore<TextSegment> getEmbeddingStoreByStoreId(String storeId);

    /**
     * Retrieves an embedding store containing text segments based on the provided configuration details.
     *
     * @param aiEmbeddingStore the configuration details of the embedding store to retrieve
     * @return an instance of {@code EmbeddingStore<TextSegment>} constructed using the provided configuration
     */
    default EmbeddingStore<TextSegment> getEmbeddingStore(AiEmbeddingStore aiEmbeddingStore) {
        final var storetype = StoreType.getByCode(aiEmbeddingStore.getStoreType());
        if (StoreType.PGVector.equals(storetype)) {
            return buildPgVector(aiEmbeddingStore);
        }
        return null;
    }

    private PgVectorEmbeddingStore buildPgVector(AiEmbeddingStore store) {
        final var storeBuilder = PgVectorEmbeddingStore.builder();
        if (Objects.equals("0", store.getConfType())) {
            final var split = store.getApiKey().split(":");
            storeBuilder
                    .createTable(true)
                    .dropTableFirst(true)
                    .host(store.getHost())
                    .port(store.getPort())
                    .user(split[0])
                    .password(split[1])
                    .database(store.getExtData())
                    .table(store.getExtData())
                    .dimension(384)
                    .build();
            storeBuilder
                    .createTable(true)
            ;
        }
        return storeBuilder.build();
    }

}
